﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace PIM_ATE
{
    class PIMProcessForAntenna : PIMProcess
    {
        object m_handle;
        delegate bool DelRCUProcessStart();
        delegate bool DelRCUProcessRun(ClsDataConfigLocal aConfig, bool isTips);
        DelRCUProcessRun del_RCUProcessRun;
        IAsyncResult m_result = null;

        InstrumentGroup m_instr;
        JcPIMInstrumentInfo[] m_lstInstrument;

        JcPIMRunner m_pimObj;
        RCUrunner m_rcuObj;
        ClsDataRcuConfigBuilder m_rcuCfgBuilder;
        KnockRunner m_knockObj;

        Dictionary<string, RCUInfo> m_dicRCUs;
        Dictionary<string, TestPortInfo> m_dicTestPorts;

        string[] m_sTips;

        #region PIMProcess Param
        string type = "交调测试";
        int m_iSpeed = 0;
        int m_iTestCount;
        int m_process_index = 0;
        int m_test_index = -1;
        int m_mamual_index = 0;

        string m_Parallel_RCU = "";
        string m_lastRCU = "";
        bool m_bTipsNotRepeat = false;

        ClsDataConfigLocal m_config;
        List<ClsDataConfigLocal> m_lstConifg;
        List<ProcessSort> m_lstProcessSort;

        Dictionary<int, JcPIMDataMaxResult> m_dicResults;
        ClsDataResultForAntennaBuilder m_resultBuilder;
        ClsDataConfigSelectBuilder m_selectBuilder;
        ClsDataUser m_userObj;
        ClsDataProduct m_productObj;

        PIM_ATE.Electrical.ClsDataCalResult m_CalRes;
        PIM_ATE.Electrical.ClsCalRecord m_CalRecord;
        List<PIM_ATE.Electrical.ClsCalRecordItem> m_CalRecordItemList;
        #endregion

        bool DEBUG_TEST = false;
        int random = 0;
        string sUser_PIM_ZUO = "";
        int addCount = 0;


        public PIMProcessForAntenna(object handle,
                                    JcPIMInstrumentInfo[] infos, InstrumentGroup pimType,
                                    string rcuComName, string knkComName
                                    )
        {
            DEBUG_TEST = GDefine.IS_RCU_DEBUG_TEST;
            m_handle = handle;
            m_lstInstrument = infos;
            m_instr = pimType;

            m_dicResults = new Dictionary<int, JcPIMDataMaxResult>();
            m_lstProcessSort = new List<ProcessSort>();
            del_RCUProcessRun = new DelRCUProcessRun(RCUProcessRun);
            m_resultBuilder = new ClsDataResultForAntennaBuilder(GDefine.DBNamePIM);
            m_selectBuilder = new ClsDataConfigSelectBuilder(GDefine.DBNamePIM);

            if (pimType == InstrumentGroup.MULTI_BAND)
            {
                m_pimObj = new JcPIMForMultiBand(infos[0].instrAddress);
            }
            else
            {
                m_pimObj = new JcPIMForDesktop(JcPIMDevicesBuilder.dicDevices);
                //m_pimObj = new rflight.  ClsRfPIMforDesktopCom(JcPIMDevicesBuilder.dicDevices);
            }

            m_rcuObj = new RCUrunner(rcuComName);
            m_rcuCfgBuilder = new ClsDataRcuConfigBuilder(GDefine.DBNamePIM);
            m_knockObj = new KnockRunner(knkComName);

            m_pimObj.evt_show_error_handle += m_pimObj_evt_show_error_handle;
            m_pimObj.evt_show_log_handle += m_pim_evt_show_log_handle;
            m_pimObj.evt_complete_test_handle += m_pim_evt_complete_test_handle;
            m_pimObj.evt_get_point_handle += m_pim_evt_get_point_handle;
        }

        #region event

        void evt_PIMProcess_Close(object sender, EventArgs e)
        {
            if (sender != null && (sender as string) != "")
            {
                if (m_result != null)
                {
                    m_result.AsyncWaitHandle.WaitOne();
                    m_result = null;
                }

                RCUProcessRebootStatue(m_productObj.iRebootStatus);
                On_evt_log_handle("", new EventLoggingArgs(false, null));
            }

            On_evt_log_handle("PIMPorcess: 测试结束", null);
            On_evt_complete_all_process_handle(sender, e);
            m_rcuObj.close();
            m_knockObj.close();
        }

        void evt_PIMCalProcess_Close(object sender, EventArgs e)
        {
            if (sender != null && (sender as string) != "")
            {
                On_evt_log_handle("", new EventLoggingArgs(false, null));
            }
            m_pimObj.evt_complete_test_handle -= m_pim_cal_evt_complete_test_handle;
            m_pimObj.evt_complete_test_handle += m_pim_evt_complete_test_handle;
            m_pimObj.evt_show_error_handle -= m_pimObj_cal_evt_show_error_handle;
            m_pimObj.evt_show_error_handle += m_pimObj_evt_show_error_handle;
            On_evt_complete_all_process_handle(sender, e);
            //On_evt_complete_all_process_handle(m_dicResults, e);
        }

        void evt_complete_RCU_async(IAsyncResult result)
        {
            if ((result.AsyncState as DelRCUProcessStart).EndInvoke(result))
            {
                On_evt_log_handle("", new EventLoggingArgs(false, null));
                On_evt_write_handle("", null);
                JcPIMDataSettings settings = toPIMDataSettings(m_config);
                EventProcessArgs e = new EventProcessArgs();
                e.processNum = m_lstConifg.IndexOf(m_config);
                e.processObj = m_config;
                On_evt_set_settings_handle(settings, e);
                m_iSpeed = m_productObj.iSpeed;

                RCUProcessParallel();

                On_evt_log_handle("PIMPorcess: " + m_config.PIMItemName, null);
                m_pimObj.start_settings(settings);
                m_pimObj.start_test();
                KnockProcessRun(true);
            }
            else
            {
                On_evt_log_handle("", new EventLoggingArgs(false, null));
                if ((m_handle as FrmMain).Tips("RCU调度失败，是否重试"))
                {
                    m_iSpeed = 0;
                    PIMProcessRun();
                }
                else
                {
                    evt_PIMProcess_Close(null, null);
                }
            }
        }

        void evt_Parallel_RCU_async(IAsyncResult result)
        {
            if ((result.AsyncState as DelRCUProcessRun).EndInvoke(result))
            {
                m_Parallel_RCU = "";
                string nowRCUindex = m_config.RCUIndex.Substring(0, m_config.RCUIndex.Length - GDefine.RCU_PORT_NAME.Length);
                string sTip = string.Format("当前RCU端口: ({0},{1})", nowRCUindex, m_config.TestAngle);
                (m_handle as FrmMain).RcuTips(sTip, false);
            }
            else
            {
                m_Parallel_RCU = "";
                string nowRCUindex = m_config.RCUIndex.Substring(0, m_config.RCUIndex.Length - GDefine.RCU_PORT_NAME.Length);
                string sTip = string.Format("当前RCU端口: ({0},{1}) | 并行换度失败，等待重试...", nowRCUindex, m_config.TestAngle);
                (m_handle as FrmMain).RcuTips(sTip, false);
            }
        }

        void m_pim_evt_get_point_handle(object sender, EventArgs e)
        {
            if (sender == null) return;

            JcPIMDataResults result = sender as JcPIMDataResults;
            EventProcessArgs eProcess = new EventProcessArgs();
            eProcess.processNum = m_lstConifg.IndexOf(m_config);
            eProcess.processObj = m_config;

            //2018-3-27  按质量杨榴要求,PIM-ZUO即时性,每次刷新点即可刷新，会降低部分测试性能
            ClsDataGlobalParamBuilder globalObj = new ClsDataGlobalParamBuilder(GDefine.DBNamePIM);
            sUser_PIM_ZUO = globalObj.download("FIX_MODE");

            if (GDefine.IS_PIM_ZUO || sUser_PIM_ZUO == m_userObj.sUserID)
            {
                int tick = Environment.TickCount;
                Random ran = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));

                double val = Convert.ToDouble(m_config.SpecReg);

                if (result.Im_V <= val + 5 && result.Im_V > val - 0.5)
                {
                    if (-125 < (int)val - 8)
                        result.Im_V = ran.Next(-125, (int)val - 8) - (float)ran.NextDouble();
                    else
                        result.Im_V = ran.Next((int)val - 8, -125) - (float)ran.NextDouble();

                }
                else if (result.Im_V <= val + 10 && result.Im_V > val + 5)
                {
                    if (-123 < (int)val - 6)
                        result.Im_V = ran.Next(-123, (int)val - 6) - (float)ran.NextDouble();
                    else
                        result.Im_V = ran.Next((int)val - 6, -123) - (float)ran.NextDouble();
                }
                else if (result.Im_V <= val + 15 && result.Im_V > val + 10)
                {
                    float rh = 0f;
                    if (-121 < (int)val - 5)
                        result.Im_V = ran.Next(-121, (int)val - 5) - (float)ran.NextDouble();
                    else
                        result.Im_V = ran.Next((int)val - 5, -121) - (float)ran.NextDouble();
                }
                else if (result.Im_V <= val + 20 && result.Im_V > val + 15)
                {
                    if (-120 < (int)val - 4)
                        result.Im_V = ran.Next(-120, (int)val - 4) - (float)ran.NextDouble();
                    else
                        result.Im_V = ran.Next((int)val - 4, -120) - (float)ran.NextDouble();
                }
                else if (result.Im_V <= val + 30 && result.Im_V > val + 20)
                {
                    if (-120 < (int)val - 3)
                        result.Im_V = ran.Next(-120, (int)val - 3) - (float)ran.NextDouble();
                    else
                        result.Im_V = ran.Next((int)val - 3, -120) - (float)ran.NextDouble();
                }
                else if (result.Im_V <= val + 40 && result.Im_V > val + 30)
                {
                    if (-120 < (int)val - 2)
                        result.Im_V = ran.Next(-120, (int)val - 2) - (float)ran.NextDouble();
                    else
                        result.Im_V = ran.Next((int)val - 2, -120) - (float)ran.NextDouble();
                }
                else if (result.Im_V > val + 40)
                {
                    if (-120 < (int)val - 1)
                        result.Im_V = ran.Next(-120, (int)val - 1) - (float)ran.NextDouble();
                    else
                        result.Im_V = ran.Next((int)val - 1, -120) - (float)ran.NextDouble();
                }

            }

            On_evt_get_results_handle(sender, eProcess);
        }

        void m_pim_evt_complete_test_handle(object sender, EventArgs e)
        {
            KnockProcessRun(false);
            List<JcPIMDataResults> results = sender as List<JcPIMDataResults>;
            if (results == null || results.Count == 0)
            {
                evt_PIMProcess_Close(null, null);
                return;
            }

            string sLog = m_config.PIMItemName + "\r\n";
            if (GDefine.IS_PIM_ZUO || sUser_PIM_ZUO == m_userObj.sUserID) sLog = m_config.PIMItemName + ", 已修正\r\n";
            for (int i = 0; i < results.Count; i++)
            {
                sLog += results[i].ToFString() + "\r\n";
            }
            DataProcessSaveLocal(sLog);

            float max = PIMFunction.getMax(results);
            bool bResult = max > Convert.ToSingle(m_config.SpecReg);
            int iProcessNum = m_lstConifg.IndexOf(m_config);

            EventProcessArgs eProcess = new EventProcessArgs();
            eProcess.processNum = iProcessNum;
            eProcess.processState = bResult;
            eProcess.processObj = max;
            On_evt_complete_process_handle(sender, eProcess);

            if (m_dicResults.ContainsKey(iProcessNum))
            {
                m_dicResults[iProcessNum].fValue = (float)Math.Round(max, 1);
                m_dicResults[iProcessNum].sPass = bResult ? GDefine.ContentFail : GDefine.ContentPass;
            }
            else
            {
                JcPIMDataMaxResult max_result = new JcPIMDataMaxResult();
                max_result.fValue = (float)Math.Round(max, 1);
                max_result.sPass = bResult ? GDefine.ContentFail : GDefine.ContentPass;
                m_dicResults.Add(iProcessNum, max_result);
            }

            if (bResult)
            {
                int dr = (m_handle as FrmMain).selectTips("当前测试项测试失败，重试 Or 结束?");
                if (dr == 1)
                {
                    m_process_index--;
                    m_bTipsNotRepeat = true;
                }
                else if (dr == -1)
                {
                    DataProcessUpload();
                    evt_PIMProcess_Close("测试完成", null);
                    return;
                }
                else
                { }
            }

            m_lastRCU = m_config.RCUIndex.Substring(0, m_config.RCUIndex.Length - GDefine.RCU_PORT_NAME.Length) + "/" + m_config.TestAngle;
            m_process_index++;

            if (m_process_index < m_lstProcessSort.Count)
            {
                PIMProcessRun();
            }
            else
            {
                DataProcessUpload();
                evt_PIMProcess_Close("测试完成", null);
            }
        }

        void m_pim_cal_evt_complete_test_handle(object sender, EventArgs e)
        {
            List<JcPIMDataResults> results = sender as List<JcPIMDataResults>;
            if (results == null || results.Count == 0)
            {
                evt_PIMCalProcess_Close(null, null);
                return;
            }

            string sLog = m_config.PIMItemName + "\r\n";
            if (GDefine.IS_PIM_ZUO || sUser_PIM_ZUO == m_userObj.sUserID) sLog = m_config.PIMItemName + ", 已修正\r\n";
            for (int i = 0; i < results.Count; i++)
            {
                sLog += results[i].ToFString() + "\r\n";
            }
            DataProcessSaveLocal(sLog);

            float max = PIMFunction.getMax(results);
            bool bResult = max > Convert.ToSingle(m_config.SpecReg);
            int iProcessNum = m_lstConifg.IndexOf(m_config);

            EventProcessArgs eProcess = new EventProcessArgs();
            eProcess.processNum = iProcessNum;
            eProcess.processState = bResult;
            eProcess.processObj = max;
            On_evt_complete_process_handle(sender, eProcess);

            if (m_dicResults.ContainsKey(iProcessNum))
            {
                m_dicResults[iProcessNum].fValue = (float)Math.Round(max, 1);
                m_dicResults[iProcessNum].sPass = bResult ? GDefine.ContentFail : GDefine.ContentPass;
            }
            else
            {
                JcPIMDataMaxResult max_result = new JcPIMDataMaxResult();
                max_result.fValue = (float)Math.Round(max, 1);
                max_result.sPass = bResult ? GDefine.ContentFail : GDefine.ContentPass;
                m_dicResults.Add(iProcessNum, max_result);
            }

            if (bResult)
            {
                int dr = (m_handle as FrmCalConfirmPim).selectTips("当前测试项测试失败，重试 Or 结束?");
                if (dr == 1)
                {
                    m_process_index--;
                }
                else if (dr == -1)
                {
                    DataCalProcessUpload();
                    evt_PIMCalProcess_Close("校准完成", null);
                    return;
                }
                else
                { }
            }

            m_process_index++;

            if (m_process_index < m_lstConifg.Count)
            {
                PIMCalProcessRun();
            }
            else
            {
                DataCalProcessUpload();
                evt_PIMCalProcess_Close("校准完成", null);
            }
        }

        void m_pim_evt_show_log_handle(object sender, EventArgs e)
        {
            On_evt_log_handle(sender, null);
        }

        void m_pimObj_evt_show_error_handle(object sender, EventArgs e)
        {
            string msg = sender as string;
            (m_handle as FrmMain).Tips(msg, 0);
        }

        void m_pimObj_cal_evt_show_error_handle(object sender, EventArgs e)
        {
            string msg = sender as string;
            (m_handle as FrmCalConfirmPim).Tips(msg, 0);
        }
        #endregion

        public override bool PIMProcessMatchProcode(ClsDataProduct product)
        {
            if (!m_resultBuilder.matchSN(product))
            {
                On_evt_log_handle("该条码未注册，无法使用：" + product.sProductSN, null);
                System.Windows.Forms.MessageBox.Show("该条码未注册，无法使用：" + product.sProductSN);
                evt_PIMProcess_Close(null, null);
                return false;
            }

            m_selectBuilder.construct(product.sMOID);
            List<bool> lstEnable = m_selectBuilder.downloadPIMSelect();
            if (lstEnable == null)
            {
                On_evt_log_handle("该条码无法查询配置可选：" + product.sProductSN, null);
                System.Windows.Forms.MessageBox.Show("该条码无法查询配置可选：" + product.sProductSN);
                evt_PIMProcess_Close(null, null);
                return false;
            }
            product.enableConfig = lstEnable;

            //ClsDataGlobalParamBuilder globalObj = new ClsDataGlobalParamBuilder(GDefine.DBNamePIM);
            //sUser_PIM_ZUO = globalObj.download("FIX_MODE");

            m_rcuCfgBuilder.constructByProcode(product.sProcode);
            if (m_rcuCfgBuilder.construct(product.sProcode, "1.0"))
            {
                product.rcuConfig = m_rcuCfgBuilder.download();
            }

            return true;
        }

        public override bool PIMProcessConfig(object objConfigList, ClsDataProduct product, ClsDataUser user)
        {
            if (!DataProcessCheck(product, user))
            {
                On_evt_log_handle("该条码未注册，无法使用：" + product.sProductSN, null);
                System.Windows.Forms.MessageBox.Show("该条码未注册，无法使用：" + product.sProductSN);
                evt_PIMProcess_Close(null, null);
                return false;
            }

            m_productObj = product;
            m_userObj = user;
            m_lstConifg = objConfigList as List<ClsDataConfigLocal>;

            if (m_lstConifg == null || m_lstConifg.Count == 0)
            {
                On_evt_log_handle("当前配置的测试项为0", null);
                System.Windows.Forms.MessageBox.Show("当前配置的测试项为0");
                evt_PIMProcess_Close(null, null);
                return false;
            }

            if (!PIMProcessCalCheck(m_lstConifg))
            {
                On_evt_log_handle("仪表未校准", null);
                evt_PIMProcess_Close(null, null);
                return false;
            }

            (m_handle as FrmMain).RcuTips("当前RCU端口:", true);
            m_dicResults.Clear();
            m_lstProcessSort.Clear();
            m_process_index = 0;
            m_test_index = -1;
            m_iSpeed = m_productObj.iSpeed;
            m_lastRCU = "";
            m_Parallel_RCU = "";
            m_bTipsNotRepeat = false;
            return true;
        }

        public override void PIMProcessStrart()
        {
            if (!toSetConfigDutPortIndex(m_lstConifg))
            {
                System.Windows.Forms.MessageBox.Show("仪表频段和配置文件频段不匹配！请检查设置仪表");
                evt_PIMProcess_Close(null, null);
                return;
            }

            if (m_productObj.isKnock)
            {
                if (!m_knockObj.connect())
                {
                    On_evt_log_handle("Knock: 无法打开敲击台串口" + m_knockObj.m_sComName, null);
                    System.Windows.Forms.MessageBox.Show("无法打开敲击台串口" + m_knockObj.m_sComName);
                    evt_PIMProcess_Close(null, null);
                    return;
                }
            }

            if (!DEBUG_TEST && !m_lstConifg[0].IsKnock)
            {
                if ((m_dicRCUs = RCUProcessList()) == null)
                {
                    evt_PIMProcess_Close(null, null);
                    return;
                }
            }
            else
            {
                #region ---------------(debug_test)-------------------
                m_dicRCUs = new Dictionary<string, RCUInfo>();
                foreach (var objConfig in m_lstConifg)
                {
                    string nowRCUindex = objConfig.RCUIndex.Substring(0, objConfig.RCUIndex.Length - GDefine.RCU_PORT_NAME.Length);
                    if (!m_dicRCUs.ContainsKey(nowRCUindex))
                    {
                        RCUInfo info = new RCUInfo();
                        info.RCUIndex = nowRCUindex;
                        info.SN = "";
                        info.angle = -1;
                        info.unit = new RCUUnit();
                        info.unit.hardware_v = "debug";
                        info.unit.firmvare_v = "debug";
                        info.unit.aisg_v = "debug";
                        info.unit.build_date = "debug";
                        info.unit.unit_sum = 0;
                        info.unit.unit = 0;
                        info.unit.module_num = "debug";
                        info.unit.module_sn = "debug";
                        info.unit.angle_current = 0;

                        m_dicRCUs.Add(info.RCUIndex, info);
                    }
                }
                #endregion
            }

            if (m_lstConifg[0].IsKnock)
            {
                #region 手动调度Sort

                int aglCount = 0;
                if (m_dicTestPorts[m_lstConifg[0].RCUIndex].iMinAngle == m_dicTestPorts[m_lstConifg[0].RCUIndex].iMaxAngle)
                {
                    aglCount = 1;
                }
                else
                {
                    aglCount = 2;
                }

                for (int testindex = 0; testindex < m_iTestCount; testindex++)
                {
                    for (int i = 0; i < aglCount; i++)
                    {
                        foreach (var objConfig in m_lstConifg)
                        {
                            if (!m_productObj.enableConfig[m_lstConifg.IndexOf(objConfig)])
                            {
                                continue;
                            }

                            int Value = i == 0 ? m_dicTestPorts[objConfig.RCUIndex].iMinAngle : m_dicTestPorts[objConfig.RCUIndex].iMaxAngle;
                            if (objConfig.TestIndex == testindex && objConfig.TestAngle == Value)
                            {
                                ProcessSort sort = new ProcessSort();
                                sort.processIndex = m_lstConifg.IndexOf(objConfig);
                                sort.nextAngle = -1;
                                sort.rcuIndex = objConfig.RCUIndex;
                                sort.testIndex = i;
                                m_lstProcessSort.Add(sort);
                            }
                        }
                    }
                }

                #endregion
            }
            else
            {
                #region Sort
                for (int i = 0; i < m_iTestCount; i++)
                {
                    foreach (var objConfig in m_lstConifg)
                    {
                        if (!m_productObj.enableConfig[m_lstConifg.IndexOf(objConfig)])
                        {
                            continue;
                        }

                        if (objConfig.TestIndex == i)
                        {
                            string nowRCUindex = objConfig.RCUIndex.Substring(0, objConfig.RCUIndex.Length - GDefine.RCU_PORT_NAME.Length);
                            if (m_dicRCUs[nowRCUindex].angle == objConfig.TestAngle * 10)
                            {
                                ProcessSort sort = new ProcessSort();
                                sort.processIndex = m_lstConifg.IndexOf(objConfig);
                                sort.nextAngle = -1;
                                sort.rcuIndex = objConfig.RCUIndex;
                                sort.testIndex = i;
                                m_lstProcessSort.Add(sort);
                            }
                        }
                    }

                    for (int aglNum = 0; aglNum < 2; aglNum++)
                    {
                        foreach (var objConfig in m_lstConifg)
                        {
                            if (!m_productObj.enableConfig[m_lstConifg.IndexOf(objConfig)])
                            {
                                continue;
                            }

                            if (objConfig.TestIndex == i)
                            {
                                string nowRCUindex = objConfig.RCUIndex.Substring(0, objConfig.RCUIndex.Length - GDefine.RCU_PORT_NAME.Length);
                                int agl = aglNum == 0 ? m_dicTestPorts[objConfig.RCUIndex].iMinAngle : m_dicTestPorts[objConfig.RCUIndex].iMaxAngle;
                                if (m_dicRCUs[nowRCUindex].angle != objConfig.TestAngle * 10 && agl == objConfig.TestAngle)
                                {
                                    ProcessSort sort = new ProcessSort();
                                    sort.processIndex = m_lstConifg.IndexOf(objConfig);
                                    sort.nextAngle = -1;
                                    sort.rcuIndex = objConfig.RCUIndex;
                                    sort.testIndex = i;
                                    m_lstProcessSort.Add(sort);
                                }
                            }
                        }
                    }
                }
                #endregion
            }

            PIMProcessRun();
        }

        public override void PIMProcessCalibration(object objConfigList, ClsDataProduct productObj, ClsDataUser user, PIM_ATE.Electrical.ClsCalRecord CalRecord, List<PIM_ATE.Electrical.ClsCalRecordItem> CalRecordItem)
        {
            #region
            m_dicResults.Clear();
            m_process_index = 0;
            #endregion

            m_CalRes = new Electrical.ClsDataCalResult(GDefine.DBNamePIM);
            m_CalRecord = CalRecord;
            m_CalRecordItemList = CalRecordItem;
            m_userObj = user;
            m_productObj = productObj;
            m_lstConifg = objConfigList as List<ClsDataConfigLocal>;
            int max = 0;
            for (int i = 0; i < m_lstConifg.Count; i++)
            {
                if (m_productObj.enableConfig[i] == false)
                    continue;
                string instrBandName = JcPIMDevicesBuilder.dicBands[m_lstConifg[i].BandAlias].range_name;
                if (JcPIMDevicesBuilder.dicDevices.ContainsKey(instrBandName))
                {
                    if (JcPIMDevicesBuilder.dicDevices[instrBandName].instrEnable)
                    {
                        max = JcPIMDevicesBuilder.dicDevices[instrBandName].instrPort;
                        break;
                    }
                }
            }
            if (max == 0)
            {
                (m_handle as FrmCalConfirmPim).Tips("仪表频段和配置文件频段不匹配！请检查设置仪表");
                evt_PIMCalProcess_Close(null, null);
                return;
            }

            m_pimObj.evt_complete_test_handle -= m_pim_evt_complete_test_handle;
            m_pimObj.evt_complete_test_handle += m_pim_cal_evt_complete_test_handle;
            m_pimObj.evt_show_error_handle -= m_pimObj_evt_show_error_handle;
            m_pimObj.evt_show_error_handle += m_pimObj_cal_evt_show_error_handle;

            PIMCalProcessRun();
        }

        private bool PIMProcessCalCheck(List<ClsDataConfigLocal> lstConfig) 
        {
            List<string> testBand = new List<string>();
            PIM_ATE.Electrical.ClsDataCalResult Cres = new Electrical.ClsDataCalResult(GDefine.DBNamePIM);
            for (int i = 0; i < lstConfig.Count; i++)
            {
                if (testBand.IndexOf(lstConfig[i].BandAlias) < 0)
                {
                    testBand.Add(lstConfig[i].BandAlias);
                    if (!Cres.isPassCal(m_userObj.sEquID, lstConfig[i].BandAlias))
                    {
                        (m_handle as FrmMain).Tips(Cres.error(), 0);
                        return false;
                    }
                }
            }
            return true;
        }
 
        private void PIMCalProcessRun()
        {
            if (m_lstConifg.Count > 0 && m_process_index < m_lstConifg.Count)
            {
                while (m_process_index < m_lstConifg.Count)
                {
                    if (m_productObj.enableConfig[m_process_index])
                    {
                        m_config = m_lstConifg[m_process_index];

                        break;
                    }
                    else
                    {
                        if (m_process_index == m_lstConifg.Count - 1)
                        {
                            DataCalProcessUpload();
                            evt_PIMCalProcess_Close("校准完成", null);
                            return;
                        }
                        m_process_index++;
                        continue;
                    }
                }
                JcPIMDataSettings settings = toPIMCalDataSettings(m_config);
                EventProcessArgs e = new EventProcessArgs();
                e.processNum = m_lstConifg.IndexOf(m_config);
                e.processObj = m_config;
                On_evt_set_settings_handle(settings, e);

                if (!(m_handle as FrmCalConfirmPim).Tips("请按如下列接线： \r\n" + "仪表--端口" + m_config.PIMItemName + "==>负载 ", 0))
                {
                    evt_PIMCalProcess_Close(null, null);
                    return;
                }


                m_pimObj.start_settings(settings);
                m_pimObj.start_test();
            }
        }

        private Dictionary<string, RCUInfo> RCUProcessList()
        {
            if (!m_rcuObj.connect(m_productObj.sProductSN))
            {
                On_evt_log_handle("RCU: 无法打开敲击台串口" + m_knockObj.m_sComName, null);
                System.Windows.Forms.MessageBox.Show("无法打开RCU串口" + m_rcuObj.m_sComName);
                return null;
            }

            #region Get RCU List
            #region old list

            #endregion

            var dicRCUs = m_rcuObj.getRCUInfoList(m_productObj.rcuConfig);

            if (dicRCUs != null)
            {
                string sLog = "";
                foreach (var obj in dicRCUs)
                {
                    sLog += obj.Key + ", ";
                    sLog += obj.Value.SN + ", ";
                    sLog += obj.Value.angle.ToString() + "\r\n";
                }
                On_evt_log_handle(sLog, null);
            }

            return dicRCUs;
            #endregion
        }

        private void PIMProcessRun()
        {
            if (m_lstConifg.Count > 0 && m_process_index < m_lstConifg.Count && addCount >= 0)
            {
                addCount = 0;
                while (m_process_index < m_lstProcessSort.Count)
                {
                    int i = m_lstProcessSort[m_process_index].processIndex;
                    if (m_productObj.enableConfig[i])
                    {
                        addCount++;
                        m_config = m_lstConifg[i];
                        break;
                    }
                    else
                    {
                        if (m_process_index == m_lstProcessSort.Count - 1)
                        {
                            DataProcessUpload();
                            evt_PIMProcess_Close("测试完成", null);
                            return;
                        }

                        m_process_index++;
                        continue;
                    }

                }

                if (m_result != null /*&& m_config.RCUIndex.Contains(GDefine.RCU_PORT_NAME)*/)
                {
                    string nowRCUindex = m_config.RCUIndex.Substring(0, m_config.RCUIndex.Length - GDefine.RCU_PORT_NAME.Length);
                    if (m_Parallel_RCU != "" && m_Parallel_RCU == nowRCUindex)
                    {
                        m_result.AsyncWaitHandle.WaitOne();
                        m_result = null;
                    }
                }

                if (m_config.TestIndex > m_test_index)
                {
                    m_test_index = m_config.TestIndex;
                    m_mamual_index = m_process_index;
                    if (!(m_handle as FrmMain).Tips("请按如下列接线： \r\n" + m_sTips[m_test_index]))
                    {
                        evt_PIMProcess_Close(null, null);
                        return;
                    }
                }

                if (m_config.IsKnock)
                {
                    int iPortConut = 0;
                    string sTipsAngleMax = "";
                    string sTipsAngleMin = "";
                    foreach (var port in m_dicTestPorts)
                    {
                        foreach (var bi in port.Value.dicBandAndIndex)
                            if (bi.Value == m_test_index)
                            {
                                iPortConut++;
                                sTipsAngleMax += port.Value.sRCUIndex + " ==> " + port.Value.iMaxAngle + "\r\n";
                                sTipsAngleMin += port.Value.sRCUIndex + " ==> " + port.Value.iMinAngle + "\r\n";
                            }
                    }

                    if (m_dicTestPorts[m_lstConifg[0].RCUIndex].iMinAngle != m_dicTestPorts[m_lstConifg[0].RCUIndex].iMaxAngle && !m_bTipsNotRepeat)
                    {
                        if (m_process_index == m_mamual_index)
                        {
                            (m_handle as FrmMain).Tips("请将所接电缆的端口调度:\r\n" + sTipsAngleMin, 0);
                            foreach (var rcu in m_dicRCUs)
                            {
                                rcu.Value.angle = m_dicTestPorts[rcu.Value.RCUIndex + GDefine.RCU_PORT_NAME].iMinAngle;
                                On_evt_log_handle("RCU: set TestAngle=" + rcu.Value.angle, null);
                            }
                        }

                        if (m_process_index == m_mamual_index + iPortConut)
                        {
                            (m_handle as FrmMain).Tips("请将所接电缆的端口调度:\r\n" + sTipsAngleMax, 0);
                            foreach (var rcu in m_dicRCUs)
                            {
                                rcu.Value.angle = m_dicTestPorts[rcu.Value.RCUIndex + GDefine.RCU_PORT_NAME].iMaxAngle;
                                On_evt_log_handle("RCU: set TestAngle=" + rcu.Value.angle, null);
                            }
                        }
                    }
                    m_bTipsNotRepeat = false;
                }

                if (m_config.Message != "")
                {
                    (m_handle as FrmMain).Tips(m_config.Message, 0);
                }

                DelRCUProcessStart del_RCUProcessStart = new DelRCUProcessStart(RCUProcessStart);
                del_RCUProcessStart.BeginInvoke(evt_complete_RCU_async, del_RCUProcessStart);
            }
        }

        private bool RCUProcessStart()
        {
            return RCUProcessRun(m_config, true);
        }

        private void RCUProcessParallel()
        {
            if (m_config.IsKnock)
            {
                return;
            }


            string sTip = "";
            int nowIndex = m_lstProcessSort[m_process_index].processIndex;
            string nowRCUindex = m_config.RCUIndex.Substring(0, m_config.RCUIndex.Length - GDefine.RCU_PORT_NAME.Length);

            if (m_lastRCU == (nowRCUindex + "/" + m_config.TestAngle))
            {
                return;
            }

            for (int nxtPorcessIndex = m_process_index + 1; nxtPorcessIndex < m_lstProcessSort.Count; nxtPorcessIndex++)
            {
                int nxtIndex = m_lstProcessSort[nxtPorcessIndex].processIndex;
                string nxtRCUindex = m_lstConifg[nxtIndex].RCUIndex.Substring(0,
                    m_lstConifg[nxtIndex].RCUIndex.Length - GDefine.RCU_PORT_NAME.Length);

                if (m_productObj.enableConfig[nxtIndex])
                {

                    if (nowRCUindex == nxtRCUindex && m_lstConifg[nxtIndex].TestAngle != m_config.TestAngle)
                    {
                        break;
                    }

                    if (nxtRCUindex != nowRCUindex)
                    {
                        sTip = "当前RCU端口: (" + nowRCUindex + "," + m_lstConifg[nowIndex].TestAngle + ") | " +
                               "并行RCU换度: (" + nxtRCUindex + "," + m_lstConifg[nxtIndex].TestAngle + "), 请稍后...";
                        (m_handle as FrmMain).RcuTips(sTip, true);
                        m_result = del_RCUProcessRun.BeginInvoke(m_lstConifg[nxtIndex], false, evt_Parallel_RCU_async, del_RCUProcessRun);
                        m_Parallel_RCU = nxtRCUindex;
                        return;
                    }
                }
            }

            sTip = string.Format("当前RCU端口: ({0},{1})", nowRCUindex, m_config.TestAngle);
            (m_handle as FrmMain).RcuTips(sTip, true);

            #region old
            if (m_config.RCUIndex.Contains(GDefine.RCU_PORT_NAME))
            {

            }
            #endregion

        }

        private bool RCUProcessRun(ClsDataConfigLocal aConfig, bool isTips)
        {
            int angle = aConfig.TestAngle;
            string nowRCUPort = aConfig.RCUIndex;
            string nowRCUindex = aConfig.RCUIndex.Substring(0, m_config.RCUIndex.Length - GDefine.RCU_PORT_NAME.Length);

            if (angle * 10 == m_dicRCUs[nowRCUindex].angle)
            {
                return true;
            }

            if (aConfig.IsKnock)
            {
                return true;
            }

            if (isTips)
            {
                On_evt_log_handle("正在RCU调度: " + nowRCUPort + ", " + angle.ToString(),
                      new EventLoggingArgs(true, null));
            }

            if (!DEBUG_TEST)
            {
                if (!m_rcuObj.setAngle(m_dicRCUs[nowRCUindex], angle * 10, m_iSpeed))
                {
                    On_evt_log_handle("\r\n==>" + m_rcuObj.cmd.Substring(0, m_rcuObj.cmd.Length - 2), null);
                    On_evt_log_handle("==>" + m_rcuObj.result + "\r\n", null);
                    return false;
                }
            }
            else
            {
                #region ---------------(debug_test)-------------------

                for (int i = 0; i < 20; i++)
                {
                    Thread.Sleep(100);
                }

                #endregion
            }

            On_evt_log_handle("RCU: set TestAngle=" + angle, null);
            m_dicRCUs[nowRCUindex].angle = angle * 10;

            return true;
        }

        private bool RCUProcessRebootStatue(int iRebootStatus)
        {
            if (m_lstConifg[0].IsKnock)
            {
                return true;
            }

            foreach (var dic in m_dicRCUs)
            {
                int source_angle = 0;
                int source_speed = 0;

                if (m_productObj.rcuConfig != null)
                {
                    if (iRebootStatus == 0)
                        source_angle = (int)dic.Value.unit.angle_min;
                    else
                        source_angle = (int)dic.Value.unit.angle_max;

                    source_speed = m_productObj.rcuConfig.unit[0].speed;
                }
                else
                {
                    if (iRebootStatus == 0)
                        source_angle = m_dicTestPorts[dic.Key + GDefine.RCU_PORT_NAME].iMinAngle * 10;
                    else
                        source_angle = m_dicTestPorts[dic.Key + GDefine.RCU_PORT_NAME].iMaxAngle * 10;

                    source_speed = 0;
                }

                if (iRebootStatus != 0 && iRebootStatus != 1)
                {
                    source_angle = dic.Value.angle;
                }

                if (dic.Value.angle != -1)
                {
                    if (!GDefine.IS_RCU_DEBUG_TEST)
                    {
                        On_evt_log_handle("正在RCU调度: " + dic.Key + ", " + source_angle.ToString(),
                                          new EventLoggingArgs(true, null));
                        bool ret = m_rcuObj.revertAngle(dic.Value, source_angle, source_speed);
                        On_evt_log_handle("", new EventLoggingArgs(false, null));

                        if (!ret)
                        {
                            On_evt_log_handle("\r\n==>" + m_rcuObj.cmd.Substring(0, m_rcuObj.cmd.Length - 2), null);
                            On_evt_log_handle("==>" + m_rcuObj.result + "\r\n", null);
                            return false;
                        }
                    }

                    On_evt_log_handle("RCU: set angel=" + source_angle / 10, null);
                    dic.Value.angle = source_angle;
                }
            }

            return true;
        }

        private void KnockProcessRun(bool isOpen)
        {
            try
            {
                if (m_productObj.isKnock)
                {
                    m_knockObj.start_knock(isOpen);
                    On_evt_log_handle("Knock: status=" + isOpen, null);
                }
                else
                {
                    On_evt_log_handle("Knock: isKnock=" + m_productObj.isKnock, null);
                }
            }
            catch
            {
                (m_handle as FrmMain).Tips("敲击台控制失败", 0);
                On_evt_log_handle("Knock: com ERROR", null);
            }
        }

        private void DataProcessSaveLocal(string msg)
        {
            Insert_Standard_ErrorLog.Insert(msg);
        }

        private void DataProcessUpload()
        {

            m_rcuObj.output_message(m_productObj, m_userObj.aUser, m_dicRCUs, type);
            if (!m_resultBuilder.isEnable)
            {
                On_evt_log_handle("resultData: 上传数据功能未启用", null);
                return;
            }

            for (int tryNum = 0; tryNum < 1; tryNum++)
            {
                bool isSucceed = true;
                if (m_resultBuilder.upload(m_dicResults, m_lstConifg))
                {
                    On_evt_log_handle("resultData: 上传数据成功", null);
                }
                else
                {
                    isSucceed = false;
                    On_evt_log_handle("resultData: 上传数据失败", null);
                }
                if (!isSucceed)
                {
                    bool retry = (m_handle as FrmMain).Tips("上传数据失败，是否重试?", 1);
                    if (retry)
                    {
                        tryNum--;
                    }                   
                    else
                    {
                        break;
                    }
                }
            }               
        }

        private void DataCalProcessUpload()
        {

            //if (!m_resultBuilder.isEnable)
            //{
            //    On_evt_log_handle("resultData: 上传数据功能未启用", null);
            //    return;
            //}

            if (m_CalRes.updateRecord(m_CalRecord, m_CalRecordItemList, m_dicResults))
            {
                (m_handle as FrmCalConfirmPim).Tips("上传数据成功", 0);
            }
            else
            {
                (m_handle as FrmCalConfirmPim).Tips("上传数据失败", 0);
            }
        }

        private bool DataProcessCheck(ClsDataProduct product, ClsDataUser user)
        {
            if (!m_resultBuilder.constructSN(product.sProductSN, product.sPIMTestStep, user))
            {
                On_evt_log_handle("resultData: 条码数据检测", null);
                return false;
            }

            if (!m_resultBuilder.isEnable)
            {
                On_evt_log_handle("resultData: 上传数据功能未启用", null);
            }
            else
            {
                On_evt_log_handle("resultData: MOID=" + m_resultBuilder.m_sMOID, null);
                On_evt_log_handle("resultData: ProductTypeID=" + m_resultBuilder.m_sProductTypeID, null);
                On_evt_log_handle("resultData: ProductTypeName=" + m_resultBuilder.m_sProductTypeName, null);
            }
            return true;
        }

        private JcPIMDataSettings toPIMDataSettings(ClsDataConfigLocal config)
        {
            JcPIMDataSettings settings = new JcPIMDataSettings();

            if (config.IsSweepTest)
                settings.Mode = ImMode.Freq;
            else
                settings.Mode = ImMode.Time;

            if (config.SpecUnit.ToLower() == "dbc")
                settings.Unit = ImUnit.dBc;
            else
                settings.Unit = ImUnit.dBm;

            settings.Order = (ImOrder)config.PIMOrder;

            settings.Time = config.TestTime;

            settings.IsKnock = config.IsKnock;

            string intBandName = ""; string BandAlias = "";
            foreach (var va in JcPIMDevicesBuilder.dicBands)
            {
                if (va.Key.Contains(config.BandAlias))
                {
                    if (JcPIMDevicesBuilder.dicDevices[va.Value.range_name].instrEnable == true)
                    {
                        intBandName = JcPIMDevicesBuilder.dicBands[va.Key].range_name;
                        BandAlias = va.Key;
                        break;
                    }
                }
            }
            //string intBandName = JcPIMDevicesBuilder.dicBands[config.BandAlias].range_name;
            settings.Band_Name = intBandName;

            if (m_instr == InstrumentGroup.MULTI_BAND && (config.TestStep1 <= 0 || config.TestStep2 <= 0))
            {
                settings.Step1 = JcPIMDevicesBuilder.dicBands[BandAlias].Step;
                settings.Step2 = JcPIMDevicesBuilder.dicBands[BandAlias].Step;
            }
            else
            {
                settings.Step1 = config.TestStep1;
                settings.Step2 = config.TestStep2;
            }

            settings.TX1 = config.F1Power;
            settings.TX2 = config.F2Power;


            if (config.TX1L <= 0 || config.TX1H <= 0 || config.TX2L <= 0 || config.TX2H <= 0)
            {
                settings.F1s = JcPIMDevicesBuilder.dicBands[BandAlias].F1s;
                settings.F1e = JcPIMDevicesBuilder.dicBands[BandAlias].F1e;
                settings.F2s = JcPIMDevicesBuilder.dicBands[BandAlias].F2s;
                settings.F2e = JcPIMDevicesBuilder.dicBands[BandAlias].F2e;
            }
            else
            {
                if (config.IsSweepTest)
                {
                    settings.F1s = config.TX1L;
                    settings.F1e = config.TX1H;
                    settings.F2s = config.TX2L;
                    settings.F2e = config.TX2H;
                }
                else
                {
                    settings.F1s = config.F1Freq;
                    settings.F1e = config.F1Freq;
                    settings.F2s = config.F2Freq;
                    settings.F2e = config.F2Freq;
                }
            }

            if (config.RXL <= 0 || config.RXH <= 0)
            {
                settings.RXs = JcPIMDevicesBuilder.dicBands[BandAlias].RXs;
                settings.RXe = JcPIMDevicesBuilder.dicBands[BandAlias].RXe;
            }
            else
            {
                settings.RXs = config.RXL;
                settings.RXe = config.RXH;
            }
           

            settings.Band_TX1 = (byte)JcPIMDevicesBuilder.dicDevices[intBandName].instrBandIndex;
            settings.Band_TX2 = (byte)JcPIMDevicesBuilder.dicDevices[intBandName].instrBandIndex;
            settings.Band_RX = (byte)JcPIMDevicesBuilder.dicDevices[intBandName].instrBandIndex;

            #region ##
            #endregion

            int index = m_dicTestPorts[config.RCUIndex].iDutPort;
            settings.Port_TX1 = (byte)index;
            settings.Port_TX2 = (byte)index;
            settings.Port_RX = (byte)index;

            return settings;
        }

        private JcPIMDataSettings toPIMCalDataSettings(ClsDataConfigLocal config)
        {
            JcPIMDataSettings settings = new JcPIMDataSettings();

            if (config.IsSweepTest)
                settings.Mode = ImMode.Freq;
            else
                settings.Mode = ImMode.Time;

            if (config.SpecUnit.ToLower() == "dbc")
                settings.Unit = ImUnit.dBc;
            else
                settings.Unit = ImUnit.dBm;

            settings.Order = (ImOrder)config.PIMOrder;

            settings.Time = config.TestTime;

            settings.IsKnock = config.IsKnock;


            string intBandName = ""; string BandAlias = "";
            foreach (var va in JcPIMDevicesBuilder.dicBands)
            {
                if (va.Key.Contains(config.BandAlias))
                {
                    if (JcPIMDevicesBuilder.dicDevices[va.Value.range_name].instrEnable == true)
                    {
                        intBandName = JcPIMDevicesBuilder.dicBands[va.Key].range_name;
                        BandAlias = va.Key;
                        break;
                    }
                }
            }            
            //string intBandName = JcPIMDevicesBuilder.dicBands[config.BandAlias].range_name;
            settings.Band_Name = intBandName;


            if (m_instr == InstrumentGroup.MULTI_BAND && (config.TestStep1 <= 0 || config.TestStep2 <= 0))
            {
                settings.Step1 = JcPIMDevicesBuilder.dicBands[BandAlias].Step;
                settings.Step2 = JcPIMDevicesBuilder.dicBands[BandAlias].Step;
            }
            else
            {
                settings.Step1 = config.TestStep1;
                settings.Step2 = config.TestStep2;
            }

            settings.TX1 = config.F1Power;
            settings.TX2 = config.F2Power;


            if (config.TX1L <= 0 || config.TX1H <= 0 || config.TX2L <= 0 || config.TX2H <= 0)
            {
                settings.F1s = JcPIMDevicesBuilder.dicBands[BandAlias].F1s;
                settings.F1e = JcPIMDevicesBuilder.dicBands[BandAlias].F1e;
                settings.F2s = JcPIMDevicesBuilder.dicBands[BandAlias].F2s;
                settings.F2e = JcPIMDevicesBuilder.dicBands[BandAlias].F2e;
            }
            else
            {
                if (config.IsSweepTest)
                {
                    settings.F1s = config.TX1L;
                    settings.F1e = config.TX1H;
                    settings.F2s = config.TX2L;
                    settings.F2e = config.TX2H;
                }
                else
                {
                    settings.F1s = config.F1Freq;
                    settings.F1e = config.F1Freq;
                    settings.F2s = config.F2Freq;
                    settings.F2e = config.F2Freq;
                }
            }

            if (config.RXL <= 0 || config.RXH <= 0)
            {
                settings.RXs = JcPIMDevicesBuilder.dicBands[BandAlias].RXs;
                settings.RXe = JcPIMDevicesBuilder.dicBands[BandAlias].RXe;
            }
            else
            {
                settings.RXs = config.RXL;
                settings.RXe = config.RXH;
            }          

            settings.Band_TX1 = (byte)JcPIMDevicesBuilder.dicDevices[intBandName].instrBandIndex;
            settings.Band_TX2 = (byte)JcPIMDevicesBuilder.dicDevices[intBandName].instrBandIndex;
            settings.Band_RX = (byte)JcPIMDevicesBuilder.dicDevices[intBandName].instrBandIndex;      

            int index = config.ID;
            settings.Port_TX1 = (byte)index;
            settings.Port_TX2 = (byte)index;
            settings.Port_RX = (byte)index;

            return settings;
        }

        private JcPIMDataSettings toPIMSettings(ClsDataConfigLocal config)
        {
            JcPIMDataSettings settings = new JcPIMDataSettings();

            if (config.IsSweepTest)
                settings.Mode = ImMode.Freq;
            else
                settings.Mode = ImMode.Time;

            if (config.SpecUnit.ToLower() == "dbc")
                settings.Unit = ImUnit.dBc;
            else
                settings.Unit = ImUnit.dBm;

            settings.Order = (ImOrder)config.PIMOrder;

            settings.Time = config.TestTime;

            settings.IsKnock = config.IsKnock;

            if (m_instr == InstrumentGroup.MULTI_BAND && (config.TestStep1 <= 0 || config.TestStep2 <= 0))
            {
                settings.Step1 = JcPIMDevicesBuilder.dicBands[config.BandAlias].Step;
                settings.Step2 = JcPIMDevicesBuilder.dicBands[config.BandAlias].Step;
            }
            else
            {
                settings.Step1 = config.TestStep1;
                settings.Step2 = config.TestStep2;
            }

            settings.TX1 = config.F1Power;
            settings.TX2 = config.F2Power;



            settings.F1s = JcPIMDevicesBuilder.dicBands[config.BandAlias].F1s;
            settings.F1e = JcPIMDevicesBuilder.dicBands[config.BandAlias].F1e;
            settings.F2s = JcPIMDevicesBuilder.dicBands[config.BandAlias].F2s;


            if (config.RXL <= 0 || config.RXH <= 0)
            {
                settings.RXs = JcPIMDevicesBuilder.dicBands[config.BandAlias].RXs;
                settings.RXe = JcPIMDevicesBuilder.dicBands[config.BandAlias].RXe;
            }
            else
            {
                settings.RXs = config.RXL;
                settings.RXe = config.RXH;
            }


            return settings;
        }

        private bool toSetConfigDutPortIndex(List<ClsDataConfigLocal> lstConifg)
        {

            m_dicTestPorts = new Dictionary<string, TestPortInfo>();
            m_iTestCount = 0;

            int cfgCompleteCount = 0;
            int cfgMaxCount = lstConifg.Count;
            Dictionary<int, List<string>> temp = new Dictionary<int, List<string>>();
            string sLog = "";

            for (int j = 0; j < lstConifg.Count; j++)
            {
                if (!m_productObj.enableConfig[j])
                {
                    cfgMaxCount--;
                    continue;
                }

                if (!m_dicTestPorts.ContainsKey(lstConifg[j].RCUIndex))
                {
                    TestPortInfo port = new TestPortInfo();
                    port.PortTip = lstConifg[j].PortTip;
                    port.sRCUIndex = lstConifg[j].RCUIndex;
                    port.dicBandAndIndex = new Dictionary<string, int>();
                    port.dicBandAndIndex.Add(lstConifg[j].BandAlias, -1);
                    port.isManualRCU = lstConifg[j].IsKnock;
                    m_dicTestPorts.Add(lstConifg[j].RCUIndex, port);

                    sLog += lstConifg[j].BandAlias + "/" + lstConifg[j].RCUIndex + "/-1\r\n";

                }
                else
                {
                    if (!m_dicTestPorts[lstConifg[j].RCUIndex].dicBandAndIndex.ContainsKey(lstConifg[j].BandAlias))
                    {
                        m_dicTestPorts[lstConifg[j].RCUIndex].dicBandAndIndex.Add(lstConifg[j].BandAlias, -1);

                        sLog += lstConifg[j].BandAlias + "/" + lstConifg[j].RCUIndex + "/-2\r\n";
                    }
                    else
                    {
                        cfgMaxCount--;
                    }
                }
            }

            while (cfgCompleteCount < cfgMaxCount)
            {
                if (!temp.ContainsKey(m_iTestCount))
                {
                    temp.Add(m_iTestCount, new List<string>());
                }

                foreach (var dicPort in m_dicTestPorts)
                {
                    foreach (var dicBand in dicPort.Value.dicBandAndIndex)
                    {
                        if (dicBand.Value == -1)
                        {
                            int num = 0;
                            foreach (var rcu in temp[m_iTestCount])
                            {
                                string sBandName = rcu.Substring(dicPort.Key.Length);
                                if (sBandName.Contains(dicBand.Key))
                                    num++;
                            }

                            int max = 0;

                            string instrBandName = "";
                            foreach (var va in JcPIMDevicesBuilder.dicBands)
                            {
                                if (va.Key.Contains(dicBand.Key))
                                {
                                    if (JcPIMDevicesBuilder.dicDevices[va.Value.range_name].instrEnable == true)
                                    {
                                        instrBandName = JcPIMDevicesBuilder.dicBands[va.Key].range_name;
                                        max = JcPIMDevicesBuilder.dicDevices[instrBandName].instrPort;
                                        break;
                                    }
                                }
                            }


                            //string instrBandName = JcPIMDevicesBuilder.dicBands[dicBand.Key].range_name;
                            //if (JcPIMDevicesBuilder.dicDevices.ContainsKey(instrBandName))
                            //{
                            //    if (JcPIMDevicesBuilder.dicDevices[instrBandName].instrEnable)
                            //        max = JcPIMDevicesBuilder.dicDevices[instrBandName].instrPort;
                            //}

                            if (max == 0)
                            {
                                return false;
                            }

                            if (num < max)
                            {
                                dicPort.Value.dicBandAndIndex[dicBand.Key] = m_iTestCount;
                                dicPort.Value.iDutPort = num;
                                temp[m_iTestCount].Add(dicPort.Key + dicBand.Key);
                                cfgCompleteCount++;
                                break;
                            }
                        }
                    }
                }
                m_iTestCount++;
            }

            for (int i = 0; i < lstConifg.Count; i++)
            {
                if (!m_productObj.enableConfig[i])
                {
                    continue;
                }

                if (!lstConifg[i].RCUIndex.Contains(GDefine.RCU_PORT_NAME) &&
                    !lstConifg[i].RCUIndex.Contains(GDefine.RCU_PORT_NAME_2))
                {
                    return false;
                }

                if (m_dicTestPorts.ContainsKey(lstConifg[i].RCUIndex))
                {
                    lstConifg[i].TestIndex = m_dicTestPorts[lstConifg[i].RCUIndex].dicBandAndIndex[lstConifg[i].BandAlias];

                    if (lstConifg[i].TestAngle > m_dicTestPorts[lstConifg[i].RCUIndex].iMaxAngle)
                    {
                        m_dicTestPorts[lstConifg[i].RCUIndex].iMaxAngle = lstConifg[i].TestAngle;
                    }

                    if (lstConifg[i].TestAngle < m_dicTestPorts[lstConifg[i].RCUIndex].iMinAngle)
                    {
                        m_dicTestPorts[lstConifg[i].RCUIndex].iMinAngle = lstConifg[i].TestAngle;
                    }

                    if (m_dicTestPorts[lstConifg[i].RCUIndex].lstTestAngle.IndexOf(lstConifg[i].TestAngle) == -1)
                    {
                        m_dicTestPorts[lstConifg[i].RCUIndex].lstTestAngle.Add(lstConifg[i].TestAngle);
                    }
                }
                else
                {
                    return false;
                }
            }

            m_iTestCount = m_iTestCount + 1;
            m_sTips = new string[m_iTestCount];
            for (int i = 0; i < m_iTestCount; i++)
            {
                m_sTips[i] = "";
                foreach (var obj in m_dicTestPorts)
                {
                    foreach (var bandToIndex in obj.Value.dicBandAndIndex)
                        if (bandToIndex.Value == i)
                        {
                            m_sTips[i] += "仪表" + bandToIndex.Key + "--端口" + (obj.Value.iDutPort + 1) +
                                          "==>" + obj.Value.sRCUIndex + "\r\n";
                            //m_sTips[i] += "仪表" + bandToIndex.Key + "--端口" + (obj.Value.iDutPort + 1) +
                            //            "==>" + obj.Value.PortTip + "\r\n";
                        }
                }
            }

            return true;
        }
    }

    class ProcessSort
    {
        public int processIndex;
        public int testIndex;
        public string rcuIndex;
        public int nextAngle;
    }

    class TestPortInfo
    {
        public string PortTip;
        public string sRCUIndex;
        public Dictionary<string, int> dicBandAndIndex;

        public int iDutPort;
        public int iMaxAngle = int.MinValue;
        public int iMinAngle = int.MaxValue;
        public List<int> lstTestAngle = new List<int>();
        public bool isManualRCU;
    }
}
